package com.woke.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.woke.CheckpaypswActivity;
import com.example.woke1.PhonefriendActivity;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.diyview.Alertdialogall;
import com.woke.method.Checkpaypsw;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class Caixtong1Fragment extends Fragment implements OnClickListener, OnItemClickListener {

	private View layout;
	private LayoutInflater minflater;
	private GridView mGridView;
	private TextView mTphone;//�������
	private TextView mTwhere;//
	private EditText mEphone;//�ֶ������ֻ��
	private MyApp application;
	private ImageView mIlist;
	private Czhireciver reciver;
	private boolean isshuru;//�ж��Ƿ����ֶ�����

	private String phoneno;//����Ҫ��ֵ���ֻ��
	private String phonenoing;//�����ֻ�Ź�̿��ܸı��
	private String face_price;//��ֵ��ֵ
	private String cz_price;//��ֵ�۸�

	private String province;
	private String operators;

	private ArrayList<String> list_hf = new ArrayList<String> ();
	private ArrayList<String> list_hfp = new ArrayList<String> ();
	private Chongzadapter adapter;

	private String pid;//ƽ̨���
	private String operatorsid;
	private RelativeLayout mBar;
	private View nowifi;
	private Intentnet net;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (layout == null) {
			minflater = inflater;
			layout = minflater.inflate (R.layout.cxtong1_layout, null);
			intview ();
		} else {
			ViewGroup parent = (ViewGroup) layout.getParent ();
			if (parent != null) {
				parent.removeView (layout);
			}
		}
		return layout;
	}

	private void qurraydatalist(String operatorsid) {
		AsyncHttpClient ahc = new AsyncHttpClient ();
		if (getContext () != null) {
			PersistentCookieStore myCookieStore = new PersistentCookieStore (getContext ());
			ahc.setCookieStore (myCookieStore);
		}
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "mobile");
		params.put ("a", "queryInfoByType");
		params.put ("oid", operatorsid);
		params.put ("type", "1");
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("套餐", "套餐" + response);
				try {
					String flag = response.getString ("flag");
					if (flag.equals ("success")) {
						nowifi.setVisibility (View.GONE);
						list_hf.clear ();
						list_hfp.clear ();
						JSONObject jsonObject = response.getJSONObject ("data");
						JSONObject object = jsonObject.getJSONObject ("data");
						pid = object.getString ("pid");
						String id = object.getString ("id");
						String packages = object.getString ("huafei");
						String hfprice = object.getString ("hfprice");
						String[] hf1 = packages.split ("\\|");
						for (int i = 0; i < hf1.length; i++) {
							String string = hf1[i];
							list_hf.add (string);
						}
						String[] hfp1 = hfprice.split ("\\|");
						for (int i = 0; i < hfp1.length; i++) {
							String string = hfp1[i];
							list_hfp.add (string);
						}
//						Log.e("string", hf);
					} else {
						nowifi.setVisibility (View.VISIBLE);
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}

				if (list_hf.size () > 0 && list_hfp.size () > 0) {
					adapter.notifyDataSetChanged ();
				}

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("string", responseString);
				nowifi.setVisibility (View.VISIBLE);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
				mBar.setVisibility (View.VISIBLE);
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				mBar.setVisibility (View.GONE);
			}
		});
	}

	private void cxtchongzhi(String pid) {
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (getActivity ());
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "mobile");
		params.put ("a", "huafeiChargeByType");
		params.put ("account_no", phoneno);
		params.put ("face_price", face_price);
		params.put ("money", cz_price);
		params.put ("pid", pid);
		params.put ("user_id", application.getDatas_load ().getId ());
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("充值", "充值" + response);
				try {
					String flag = response.getString ("flag");
					String info = response.getString ("info");
					if (flag.equals ("success")) {
						Toast.makeText (getActivity (), "" + info, Toast.LENGTH_SHORT).show ();
						getActivity ().finish ();
					} else {
						Toast.makeText (getActivity (), "" + info, Toast.LENGTH_SHORT).show ();
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Toast.makeText (getActivity (), "充值失败", Toast.LENGTH_SHORT).show ();
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
				mBar.setVisibility (View.VISIBLE);
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				mBar.setVisibility (View.GONE);
			}
		});
	}

	private void qurrayprivicen(final String phone) {
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (getActivity ());
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "mobile");
		params.put ("a", "queryProvince");
		params.put ("mobile", phone);
		Log.e ("params", "" + params);
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("归宿地", "" + response);
				try {
					String flag = response.getString ("flag");
					if (flag.equals ("success")) {
						JSONObject jsonObject = response.getJSONObject ("data");
						JSONObject object = jsonObject.getJSONObject ("data");
						String provinceid = object.getString ("provinceid");
						province = object.getString ("province");
						operatorsid = object.getString ("operatorsid");
						operators = object.getString ("operators");
						if (application.getDatas_load () != null && phone.equals (application.getDatas_load ()
								.getUser_login ())) {
							mTwhere.setText ("账号绑定号码" + "(" + province + operators + ")");
						} else {
							mTwhere.setText ("(" + province + operators + ")");
						}
						qurraydatalist (operatorsid);
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("responseString是对方的事", responseString);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
			}

			@Override
			public void onFinish() {
				super.onFinish ();
			}
		});
	}

	class Czhireciver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {

			Bundle extras = intent.getExtras ();
			String phoneno1 = extras.getString ("phoneno").toString ().trim ();
			if (phoneno1.equals ("phoneno")) {
				cxtchongzhi (pid);
			} else {
				if (net.isNetworkConnected (getActivity ()) == false) {
					Toast.makeText (getActivity (), "网络链接不可用", Toast.LENGTH_SHORT).show ();
					nowifi.setVisibility (View.VISIBLE);
				} else {
					qurrayprivicen (phoneno1);
				}
				if (isshuru == false) {
					mTphone.setText (phoneno1.substring (0, 3) + " " + phoneno1.substring (3, 7)
							+ " " + phoneno1.substring (phoneno1.length () - 4, phoneno1.length ()));
				} else {
					Log.e ("phoneno1", phoneno1);
					mEphone.setText (phoneno1.substring (0, 3) + " " + phoneno1.substring (3, 7)
							+ " " + phoneno1.substring (phoneno1.length () - 4, phoneno1.length ()));
//					}
				}
			}
		}
	}

	private void intview() {
		net = new Intentnet ();
		reciver = new Czhireciver ();
		IntentFilter filter = new IntentFilter ();
		filter.addAction ("com.woke.cxtongactivity");
		getActivity ().registerReceiver (reciver, filter);

		zidingy = new Alertdialogall ();

		mBar = (RelativeLayout) layout.findViewById (R.id.fmcxtf_frame1);

		application = (MyApp) getActivity ().getApplication ();
		mGridView = (GridView) layout.findViewById (R.id.fmcxtong_f1_gridview);
		adapter = new Chongzadapter ();
		mGridView.setAdapter (adapter);
		mGridView.setOnItemClickListener (this);
		mTphone = (TextView) layout.findViewById (R.id.fmcxtong_f1_phone1);
		mTwhere = (TextView) layout.findViewById (R.id.fmcxtong_f1_where);
		mEphone = (EditText) layout.findViewById (R.id.fmcxtong_f1_ephone);
		if (application.getDatas_load () != null) {
			phoneno = application.getDatas_load ().user_login;
			mTphone.setText (phoneno.substring (0, 3) + " " + phoneno.substring (3, 7)
					+ " " + phoneno.substring (phoneno.length () - 4, phoneno.length ()));
		}

		mIlist = (ImageView) layout.findViewById (R.id.fmcxtong_f1_phonelist);
		nowifi = layout.findViewById (R.id.fmcxtong_when_nowifi);
		nowifi.setOnClickListener (this);
		mIlist.setOnClickListener (this);
		mTphone.setOnClickListener (this);
		if (net.isNetworkConnected (getActivity ()) == false) {
			Toast.makeText (getActivity (), "网络链接不可用", Toast.LENGTH_SHORT).show ();
			nowifi.setVisibility (View.VISIBLE);
		} else {
			qurrayprivicen (phoneno);
		}

		mEphone.addTextChangedListener (watcher);

	}

	private TextWatcher watcher = new TextWatcher () {
		private int startwordno;
		private int endwordno;

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			startwordno = mEphone.getSelectionStart ();
			endwordno = mEphone.getSelectionEnd ();
			if (mEphone.getText ().toString ().trim ().length () > 11) {
				s.delete (startwordno - 1, endwordno);
				int tempSelection = endwordno;
				mEphone.setText (s);
				mEphone.setSelection (tempSelection);
				Log.e ("11", "11");
			} else if (mEphone.getText ().toString ().trim ().length () == 11) {
				phoneno = s.toString ().trim ();
//	    		phonenoing = phoneno;
				Log.e ("phoneno", phoneno);
				qurrayprivicen (phoneno);
			}
		}
	};
	private Alertdialogall zidingy;

	class Chongzadapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list_hf.size ();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		class Holder {
			//			ImageView mIicon;
			TextView mTmoney;
			TextView mThowmcuh;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				holder = new Holder ();
				convertView = getActivity ().getLayoutInflater ()
						.inflate (R.layout.item_gridview_czhi, null);
//				holder.mIicon = (ImageView) convertView.findViewById(R.id.item_myblind_bankicon);
				holder.mTmoney = (TextView) convertView.findViewById (R.id.item_czhiadter_money);
				holder.mThowmcuh = (TextView) convertView.findViewById (R.id.item_czhiadter_howmuch);
				convertView.setTag (holder);
			} else {
				holder = (Holder) convertView.getTag ();
			}
			String hf_str = list_hf.get (position);
			holder.mTmoney.setText (hf_str + "元");
			String hf_strp = list_hfp.get (position);
			holder.mThowmcuh.setText ("售价：" + hf_strp + "元");

			return convertView;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId ()) {
			case R.id.fmcxtong_f1_phonelist:
				isshuru = false;
				mTphone.setVisibility (View.VISIBLE);
				mEphone.setVisibility (View.GONE);
				Intent intent = new Intent (getActivity (), PhonefriendActivity.class);
				intent.putExtra ("from", "where");
				startActivity (intent);
				break;

			case R.id.fmcxtong_f1_phone1:
				isshuru = true;
				mTphone.setVisibility (View.GONE);
				mEphone.setVisibility (View.VISIBLE);
				mTwhere.setText ("");
				break;

			case R.id.fmcxtong_when_nowifi:
				if (net.isNetworkConnected (getActivity ()) == false) {
					Toast.makeText (getActivity (), "网络链接不可用", Toast.LENGTH_SHORT).show ();
					nowifi.setVisibility (View.VISIBLE);
				} else {
					qurrayprivicen (phoneno);
				}
				break;

			default:
				break;
		}
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, String phoneno, final String cz_price) {

			View view = View
					.inflate (mContext, R.layout.item_popu_cxt, null);
			view.startAnimation (AnimationUtils.loadAnimation (mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById (R.id.popowind_cxt_zhifu);
			LayoutParams params = ll_popup.getLayoutParams ();
			params.height = application.screenHigth / 3 * 2;
			params.width = application.screenWidth;
			ll_popup.setLayoutParams (params);
			ll_popup.startAnimation (AnimationUtils.loadAnimation (mContext,
					R.anim.push_bottom_in_2));

			setWidth (LayoutParams.FILL_PARENT);
			setHeight (LayoutParams.FILL_PARENT);
			setBackgroundDrawable (new BitmapDrawable ());
			setFocusable (true);
			setOutsideTouchable (true);
			setContentView (view);
			showAtLocation (view, Gravity.BOTTOM, 0, 0);
			update ();
//			popowind_cxt_zhifuok
			TextView mTextinfo = (TextView) view.findViewById (R.id.popowind_cxt_textinfo);
			TextView mTextmone = (TextView) view.findViewById (R.id.popowind_cxt_textmoney);
			mTextinfo.setText (phoneno + province + operators + cz_price + "元话费");
			mTextmone.setText (cz_price + "元");
			view.findViewById (R.id.popowind_cxt_finish)
					.setOnClickListener (new OnClickListener () {

						@Override
						public void onClick(View view) {
							dismiss ();
						}
					});
			view.findViewById (R.id.popowind_cxt_zhifuok)
					.setOnClickListener (new OnClickListener () {

						@Override
						public void onClick(View v) {
							Intent intent = new Intent (getActivity (), CheckpaypswActivity.class);
							intent.putExtra ("paymoney", cz_price);
							intent.putExtra ("cxtong", "cxtong");
							startActivity (intent);
							dismiss ();
						}
					});
		}
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Checkpaypsw check = new Checkpaypsw ();
		if (check.check (application) == true) {
			zidingy.aralogid (getActivity (), "还未设置支付密码", "前往设置？");
		} else {
			face_price = list_hf.get (arg2);
			cz_price = list_hfp.get (arg2);
			if (isshuru == false) {
				phoneno = mTphone.getText ().toString ().replace (" ", "");
			} else {
				phoneno = mEphone.getText ().toString ().replace (" ", "");
			}
			new PopupWindows (getActivity (), phoneno, cz_price);
		}

	}

}
